package com.d3works.apps.businesssupport.service;

import com.d3works.apps.businesssupport.db.ProjectAnnouncement;
import com.d3works.apps.hr.service.project.ProjectDashboardHRServiceImpl;
import com.d3works.apps.project.db.Project;
import com.d3works.apps.project.db.repo.ProjectRepository;
import com.d3works.apps.project.service.ProjectService;
import com.google.inject.Inject;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ProjectDashboardBusinessSupportServiceImpl extends ProjectDashboardHRServiceImpl {

  @Inject protected ProjectRepository projectRepo;
  @Inject protected ProjectService projectService;

  @Override
  public Map<String, Object> getData(Project project) {
    Map<String, Object> dataMap = super.getData(project);
    dataMap.put("$announcementList", getLatestNews(project));
    return dataMap;
  }

  protected List<Map<String, Object>> getLatestNews(Project project) {
    List<Map<String, Object>> newsList = new ArrayList<>();
    List<ProjectAnnouncement> announcementList = new ArrayList<>();

    projectRepo.all().filter("self.id IN ?1", projectService.getContextProjectIds()).fetch()
        .stream()
        .forEach(subProject -> announcementList.addAll(subProject.getAnnouncementList()));

    for (ProjectAnnouncement announcement :
        announcementList.stream()
            .sorted(Comparator.comparing(ProjectAnnouncement::getDate).reversed())
            .limit(6)
            .collect(Collectors.toList())) {
      Map<String, Object> announcementMap = new HashMap<>();
      announcementMap.put("id", announcement.getId());
      announcementMap.put("title", announcement.getTitle());
      announcementMap.put("createdById", announcement.getCreatedBy().getId());
      announcementMap.put("createdBy", announcement.getCreatedBy().getFullName());
      announcementMap.put("announcementDate", announcement.getDate());
      newsList.add(announcementMap);
    }
    return newsList;
  }
}
